package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC720 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public String longestWord(String[] words) {
            TreeMap<Integer, TreeSet<String>> wordMap = new TreeMap<>(Comparator.reverseOrder());
            for (String word : words) {
                if (!wordMap.containsKey(word.length())) wordMap.put(word.length(), new TreeSet<>());
                wordMap.get(word.length()).add(word);
            }

            int candidateStartIdx = wordMap.keySet().iterator().next();
            for (int idx = candidateStartIdx; idx >= 0; idx--) {
                if (!wordMap.containsKey(idx)) continue;
                TreeSet<String> candidates = wordMap.get(idx);
                for (String candidate : candidates) {
                    int i = candidate.length() - 1;
                    for (; i >= 0; i--) {
                        if (!wordMap.containsKey(i)) break;
                        if (!wordMap.get(i).contains(candidate.substring(0, i))) break;
                    }
                    if (i <= 0) return candidate;
                }
            }

            return "";
        }
    }

    public void run() {
        System.out.println(new Solution().longestWord(new String[]{"w", "wo", "wor", "worl", "world"}));
        System.out.println(new Solution().longestWord(new String[]{"a", "banana", "app", "appl", "ap", "apply", "apple"}));
    }

    public static void main(String[] args) throws Exception {
        LC720 an = new LC720();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
